<template>
  <div class="xtx-checkbox" @click="toggleChecked">
    <!-- 选中小图标 -->
    <i class="iconfont icon-checked" v-if="hasChecked"></i>
    <!-- 未选中小图标 -->
    <i v-else class="iconfont icon-unchecked"></i>
    <!-- 自定义文字 -->
    <span><slot/></span>
  </div>
</template>
<script>
import { ref, watch } from 'vue'
export default {
  name: 'XtxCheckbox',
  props: {
    modelValue: {
      type: Boolean,
      default: false
    }
  },
  setup (props, { emit }) {
    // 当前是否选中，true选中,false未选中
    const hasChecked = ref(false)
    function toggleChecked () {
      hasChecked.value = !hasChecked.value
      emit('update:modelValue', hasChecked.value)
      emit('change', hasChecked.value)
    }
    watch(
      () => {
        return props.modelValue
      },
      () => {
        hasChecked.value = props.modelValue
      },
      {
        immediate: true
      }
    )
    return { hasChecked, toggleChecked }
  }
}
</script>
<style scoped lang="less">
.xtx-checkbox {
  display: inline-block;
  margin-right: 2px;
  .icon-checked {
    color: @xtxColor;
    ~ span {
      color: @xtxColor;
    }
  }
  i {
    position: relative;
    top: 1px;
  }
  span {
    margin-left: 2px;
  }
}
</style>
